package com.zhudi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util;
import com.zhudi.commen.BaseResponse;
import com.zhudi.commen.ErrorCode;
import com.zhudi.commen.ResultUtils;
import com.zhudi.expection.BusinessException;
import com.zhudi.service.UserService;
import com.zhudi.domain.User;
import com.zhudi.mapper.UserMapper;
import com.zhudi.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Objects;

import static com.zhudi.contant.UserContant.*;

/**
* @author 朱朱朱朱蒂
* @description 针对表【user(用户信息表)】的数据库操作Service实现
* @createDate 2024-02-07 23:51:09
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 登录功能实现
     * @param username 用户名
     * @param password 密码
     * @param request 浏览器请求
     * @return 成功返回用户脱敏数据，失败返回空
     */
    @Override
    public BaseResponse<User> login(String username, String password, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(username,password)){
            return ResultUtils.Error(ErrorCode.USER_ERROR,"账户或密码为空");
        }

        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("user_name",username);
        User user = userMapper.selectOne(userQueryWrapper);
        //用户存在性检验
        if (user==null){
            return ResultUtils.Error(ErrorCode.USER_ERROR,"不存在该用户");
        }

        //密码检验
        if (!StringUtils.equals(UserUtils.getencryptPassword(password),user.getPassword())){
            return ResultUtils.Error(ErrorCode.USER_ERROR,"密码错误");

        }

        request.getSession().setAttribute(USER_LOGIN_STATE,user);;
        return ResultUtils.success(UserUtils.getSafetyUser(user),"登录成功");
    }

    /**
     * 注册功能实现
     * @param username 用户名
     * @param password 密码
     * @param confirmPassword 确认密码
     * @param request 请求
     * @return 成功的话返回用户id，失败返回空
     */
    @Override
    public BaseResponse<Integer> register(String username, String password, String confirmPassword, HttpServletRequest request) {
        //账户密码空格检测
        if (StringUtils.isAnyBlank(username,password,confirmPassword)){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户或密码存在空格");}
        //两次密码相同检测
        if (!password.equals(confirmPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不相同");
        }
        //用户名密码长度检测
        if (username.length()<USER_NAME_MIN_LENGTH){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名长度过短"+USER_PASSWORD_MIN_LENGTH);
        }

        if (password.length()<USER_PASSWORD_MIN_LENGTH){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度小于"+ USER_PASSWORD_MIN_LENGTH);
        }

        //用户名重复检测
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        if (userMapper.selectCount(queryWrapper)>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名重复");
        };

        //通过检测后将账户密码放入到数据库中
        User user = new User(username,UserUtils.getencryptPassword(password));
        int id = userMapper.insert(user);
//        todo：解决id不从1开始自增的问题

        request.getSession().setAttribute(USER_LOGIN_STATE,user);;

        return ResultUtils.success(id,"创建用户成功");
    }

    /**
     * 注销功能实现
     * @param request 浏览器的请求
     * @return 成功返回1
     */
    @Override
    public Integer logout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);

        return 1;
    }

    /**
     * 获取所有用户信息实现
     * @return 所有用户信息
     */
    @Override
    public List<User> getAllUser() {
        List<User> users = userMapper.selectList(new QueryWrapper<>());

        return users;
    }

    /**
     * 获取当前用户信息实现
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public User getCurrentUser(int userId) {
        User user = userMapper.selectById(userId);
        return UserUtils.getSafetyUser(user);
    }

    @Override
    public int update(User updateUser, User loginUser) {
        //首先是判空检查
        if(isBlank(updateUser)||isBlank(loginUser)){
            return 0;
        }
        //根据要更新用户的id和当前登录用户id比较是否是同一个id

        if(!Objects.equals(updateUser.getId(), loginUser.getId())||!isAdmin(loginUser)){
            return 0;
        }
        //todo:可以考虑是否一些参数不能修改，现在暂且设置为都可以修改。
        //如果更新的数据不为空，并且是本人或者是管理员的话，就允许修改
        return  userMapper.updateById(updateUser);


    }



    @Override
    public boolean isBlank(User user) {
        if(user==null){
            return true;
            //将id单独拆出来判断，是因为id默认值为0
        }else if(user.getId()<=0){
            return true;
        }else {

       return StringUtils.isAllBlank(user.getUserName(),user.getAvatar(),user.getNickname(),user.getPassword()
        ,user.getPhone());
        }

    }

    @Override
    public boolean isAdmin(User user) {
        if(user==null||user.getId()<=0){
            return false;
        }
        User dbUser = userMapper.selectById(user.getId());
        return dbUser.getRole()==1;
    }


}




